package com.dmgis.qxfw.dataservice.businessservice.nyfw.service.Impl;

import com.dmgis.qxfw.dataservice.businessservice.api.domain.RequestDataBySelect;
import com.dmgis.qxfw.dataservice.businessservice.api.domain.RequestDataByUpdate;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.ny.*;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.*;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.warinInfo;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.warn_signal_info;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.agri_product;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.summary_product;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.ResultObj;
import com.dmgis.qxfw.dataservice.businessservice.common.util.*;
import com.dmgis.qxfw.dataservice.businessservice.controller.ProcessRequestController;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.FileRequestService;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.MongoService1;
import com.dmgis.qxfw.dataservice.businessservice.nyfw.service.IFarmIndexService;
import com.dmgis.qxfw.dataservice.commonservice.common.DbConfig;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service("FarmIndexService")
public class FarmIndexServiceImpl implements IFarmIndexService {

    WebCtrlData wcd = new WebCtrlData();
    ProcessRequestController pc = new ProcessRequestController();
    //MongoService1 ms = new MongoService1();
    FileRequestService ms = new FileRequestService();

    private  final String operatingSystem;

    @Autowired
    public FarmIndexServiceImpl(String operatingSystem) {
        this.operatingSystem = operatingSystem;
    }
    /***
     * 得到站点信息
     * @return
     */
    @Override
    public List<StationInfo> getStationInfo() {
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<StationInfo> stationList = new ArrayList<StationInfo>();
        try {
            selectRequest.setColumns(new String[]{"stationID", "stationName"});
            selectRequest.setParam("city like '" + DbConfig.CITY + "%'");
            selectRequest.setSort(new String[]{"stationid asc"});
            selectParam.put("method", "smallscale_station");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            stationList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<StationInfo>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
        }
        return stationList;
    }

    /***
     * 得到天气预报滚屏信息
     * @return
     */
    @Override
    public String getForecast() {
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        String result = "";
        try {
            selectRequest.setColumns(new String[]{"stationid", "stationname", "longitude", "latitude", "weather1", "weather2", "maxtemp", "mintemp", "wind1", "wind2", "windd1", "windd2"});
            selectRequest.setParam("ntimes = '24' and  stationid = '" + DbConfig.STATIONIDYB + "'");
            selectParam.put("method", "forecastinfonewest_view");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            List<forecastinfo> stationList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<forecastinfo>>() {
            });

            if (stationList!=null&&stationList.size() > 0) {

                String strWeather1 = stationList.get(0).getWeather1().toString();
                String strWeather2 = stationList.get(0).getWeather2().toString();

                String strMinTemp = stationList.get(0).getMintemp().toString();
                String strMaxTemp = stationList.get(0).getMaxtemp().toString();
                if (strMinTemp == "-65535" || strMinTemp == "65535") {
                    strMinTemp = "";
                }
                if (strMaxTemp == "-65535" || strMaxTemp == "65535") {
                    strMaxTemp = "";
                }
                String windd1 = stationList.get(0).getWindd1().toString();
                String windd2 = stationList.get(0).getWindd2().toString();
                double wind1 = stationList.get(0).getWind1();
                String strWind1 = wcd.GetWeatherFs(String.format("%.0f", wind1));
                double wind2 = stationList.get(0).getWind2();
                String strWind2 = wcd.GetWeatherFs(String.format("%.0f", wind2));
                //将天气代码转换成天气现象Convert.ToDouble(str1).ToString("00");
                String strWeatherDisp = "";
                if (wcd.GetWeatherTq(String.format("%02d", Integer.parseInt(strWeather1))) == wcd.GetWeatherTq(String.format("%02d", Integer.parseInt(strWeather2)))) {
                    strWeatherDisp = wcd.GetWeatherTq(String.format("%02d", Integer.parseInt(strWeather1)));
                } else {
                    strWeatherDisp = wcd.GetWeatherTq(String.format("%02d", Integer.parseInt(strWeather1))) + " 转 " + wcd.GetWeatherTq(String.format("%02d", Integer.parseInt(strWeather2)));
                }
                String strTempDisp = "";
                if (strMinTemp == "" && strMaxTemp == "") {
                    strTempDisp = "";
                } else {
                    strTempDisp = " ,气温" + strMinTemp + "℃～" + strMaxTemp + "℃";
                }

                String strWindDisp = "";
                if (windd1.equals(windd2)) {
                    if (strWind1 == strWind2) {

                        strWindDisp = wcd.GetAllFx(windd1).toString() + strWind1;
                    } else {
                        strWindDisp = wcd.GetAllFx(windd1).toString() + strWind1 + " 转 " + strWind2;
                    }
                } else {
                    strWindDisp = wcd.GetAllFx(windd1).toString() + strWind1 + " 转 " + wcd.GetAllFx(windd2).toString() + strWind2;
                }

                result = stationList.get(0).getStationname().trim() + " 未来24小时内的天气情况： ";
                result += strWeatherDisp + strTempDisp + " , " + strWindDisp;
            }

        } catch (Exception e) {
            // TODO: handle exception
        }
        return result;
    }


    /***
     * 得到预警信息
     * @return
     */
    @Override
    public List<warn_signal_info> getWarning() {
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<warn_signal_info> warnMessageList = new ArrayList<warn_signal_info>();
        try {
            DateTime warnTime = DateTime.now().AddDays(-1);
            selectRequest = new RequestDataBySelect();
            selectRequest.setParam("bfree= 0 and announcedtime>='" + warnTime.toDateTimeString("yyyy-MM-dd HH:mm:ss") + "' and (city like '" + DbConfig.CITY + "%')");
            selectRequest.setLimit(1);
            selectRequest.setSort(new String[]{"announcedtime desc"});
            selectParam.put("method", "warn_signal_info");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            warnMessageList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<warn_signal_info>>() {
            });
        } catch (Exception e) {
        }
        return warnMessageList;
    }


    /***
     * 得到天气实况
     * @return
     */
    @Override
    public String getWeather(String stationid) {
        String result = "";
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        try {
            selectRequest.setColumns(new String[]{"observtime", "stationname", " drybulbtemp", " relhumidity", "instantwindv", " instantwindd", "stationpress", "rain"});
            selectRequest.setParam("stationid = '" + stationid + "'");
            selectParam.put("method", "msgmediumsmallscale");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            List<msgmediumsmallscale> stationList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<msgmediumsmallscale>>() {
            });
            if (stationList!=null&&stationList.size() > 0) {
                msgmediumsmallscale msgme = stationList.get(0);
                //温度
                if (msgme.getDrybulbtemp() == -65535) {
                    result = "暂无实况$";
                } else {
                    result = msgme.getDrybulbtemp().toString() + "$";
                }
                //湿度
                if (msgme.getRelhumidity() == -65535) {
                    result += "无$";
                } else {
                    result += msgme.getRelhumidity().toString() + "$";
                }

                //风速
                if (msgme.getInstantwindv() == -65535) {
                    result += "无$";
                } else {
                    result += msgme.getInstantwindv().toString() + "$";
                }
                //风向
                if (msgme.getInstantwindd() == -65535) {
                    result += "无$";
                } else {
                    result += wcd.GetAllFx(msgme.getInstantwindv().toString().trim()) + "$";
                }
                //气压
                if (msgme.getStationpress().toString().equals("0.0")) {
                    result += "无$";
                } else {
                    result += msgme.getStationpress().toString() + "$";
                }
                //雨量
                result += msgme.getRain().toString() + "$";
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH");
                result += sdf1.format(msgme.getObservtime()) + "时实况";
            }

        } catch (Exception e) {
            // TODO: handle exception
        }
        return result;
    }

    /***
     * 得到底部支持
     * @return
     */
    @Override
    public Wangzhan getSupport() {
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<Wangzhan> list = new ArrayList<Wangzhan>();
        try {
            selectRequest = new RequestDataBySelect();
            selectRequest.setParam("owner = '" + DbConfig.CITY + "'");
            selectParam.put("method", "wangzhan");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            list = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<Wangzhan>>() {
            });
        } catch (Exception e) {
        }
        if (list != null && list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    /**
     * @Description: 1.获取当前日期所有站点的所有农事活动
     * * * 2.然后根据农事活动分类来筛选出对应种类的农事活动
     * @Author: sunshine
     * @Date: 2021/7/22 14:11
     **/
    @Override
    public Object getArgiSrvFcst(String date, String timeChar, String nyStaName) {
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<AgriSrvFcst> agrisrvList = new ArrayList<AgriSrvFcst>();
        Map<String, String> result = new HashMap<>();
        try {
            selectRequest = new RequestDataBySelect();
            selectRequest.setColumns(new String[]{"farmservicesite", "indexname", "indexlevel"});
            selectRequest.setParam("forecastdate = '" + date + "' and timechar='" + timeChar + "' and farmservicesite='" + nyStaName + "'");
            selectParam.put("method", "agri_srv_fcst");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            agrisrvList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<AgriSrvFcst>>() {
            });
            //stream过滤
            List list = agrisrvList.stream().filter(t -> Objects.equals(t.getIndexname(), "灌溉")).collect(Collectors.toList());
            result.put("gg", list.size() > 0 ? ((AgriSrvFcst) list.get(0)).getIndexlevel() : "暂无数据");
            list = agrisrvList.stream().filter(t -> Objects.equals(t.getIndexname(), "喷药")).collect(Collectors.toList());
            result.put("py", list.size() > 0 ? ((AgriSrvFcst) list.get(0)).getIndexlevel() : "暂无数据");
            list = agrisrvList.stream().filter(t -> Objects.equals(t.getIndexname(), "施肥")).collect(Collectors.toList());
            result.put("sf", list.size() > 0 ? ((AgriSrvFcst) list.get(0)).getIndexlevel() : "暂无数据");
            list = agrisrvList.stream().filter(t -> Objects.equals(t.getIndexname(), "收晒")).collect(Collectors.toList());
            result.put("ss", list.size() > 0 ? ((AgriSrvFcst) list.get(0)).getIndexlevel() : "暂无数据");
        } catch (Exception e) {
            return new ResultObj("查询失败", e.getMessage(), true);
        }
        return new ResultObj("查询成功", result, true);
    }

    /**
     * @Description: 农情监控
     * @Author: sunshine
     * @Date: 2021/7/22 15:48
     **/
    @Override
    public Object getArgiMonitor(String type) {
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<AgriMoniInfo> agrisrvList = new ArrayList<AgriMoniInfo>();
        try {
            selectRequest = new RequestDataBySelect();
            selectRequest.setColumns(new String[]{"cropname", "growdatename", "warningtype", "warningtime", "stationid"});
            selectRequest.setParam("isremove=0");
            selectRequest.setSort(new String[]{"warningtime desc"});
            if (!StringUtil.IsNullOrEmpty(type)) selectRequest.setLimit(7);
            selectParam.put("method", "agri_moni_info");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            agrisrvList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<AgriMoniInfo>>() {
            });
            if (!StringUtil.IsNullOrEmpty(type)) {
                selectParam = new HashMap<String, String>();
                selectRequest = new RequestDataBySelect();
                selectRequest.setColumns(new String[]{"stationname", "stationid"});
                selectParam.put("method", "station_info");
                selectParam.put("sqlType", "select");
                selectParam.put("advCode", DbConfig.advCode);
                selectParam.put("param", JsonUtil.object2Json(selectRequest));
                message = pc.processRequest(selectParam);
                List<StationInfo> stationInfos = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<StationInfo>>() {
                });
                //连表
                for (AgriMoniInfo itema : agrisrvList) {
                    for (StationInfo itemb : stationInfos) {
                        if (itema.getStationid() == itemb.getStationid()) {
                            itema.setStationname(itemb.getStationname());
                            itema.setCropname(itema.getCropname().trim());
                            itema.setGrowdatename(itema.getGrowdatename());
                            itema.setWarningtype(itema.getWarningtype());
                        }
                    }
                }
            }
        } catch (Exception e) {
            return new ResultObj("查询失败", e.getMessage(), true);
        }
        return new ResultObj("查询成功", agrisrvList, true);
    }

    /**
     * @Description: 政务信息 文章类别和文章内容
     * @Author: sunshine
     * @Date: 2021/7/22 15:59
     **/
    @Override
    public Object getArgiZhengFa(String BigType, String type, String FirstId, String Smalltype,HttpServletRequest request) {
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<Addwendang> agrisrvList = new ArrayList<Addwendang>();
        try {
            selectRequest = new RequestDataBySelect();
            selectRequest.setColumns(new String[]{"id", "bigtype", "smalltype","content", "datamodifydate", "title", "publisher", "uploadtime", "owner", "click", "ishuandeng","picpath"});
            if (!StringUtil.IsNullOrEmpty(type) && !StringUtil.IsNullOrEmpty(BigType)) {
                selectRequest.setParam("bigtype = '" + BigType + "' and smalltype <> '7'  and smalltype <> '8' and owner = '" + DbConfig.CITY + "'");
                selectRequest.setSort(new String[]{"datamodifydate desc"});
                if (!StringUtil.IsNullOrEmpty(FirstId))
                    selectRequest.setParam(selectRequest.getParam() + " and id = '" + FirstId + "'");
            } else if (!StringUtil.IsNullOrEmpty(BigType) && !StringUtil.IsNullOrEmpty(Smalltype)) {
                selectRequest.setParam("bigtype = '" + BigType + "'  and smalltype = '" + Smalltype + "' and owner = '" + DbConfig.CITY + "'");
                selectRequest.setSort(new String[]{"datamodifydate desc"});
            } else if (!StringUtil.IsNullOrEmpty(BigType)) {
                selectRequest.setParam("bigtype = '" + BigType + "'  and smalltype <> '8' and owner = '" + DbConfig.CITY + "'");
                selectRequest.setSort(new String[]{"datamodifydate desc"});
            }
            selectParam.put("method", "addwendang");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            agrisrvList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<Addwendang>>() {
            });
            for (Addwendang wendang : agrisrvList) {
                wendang.setOwner(wendang.getOwner().trim());
                String serviceFilePath = "";
                // 下载
                String fileName = wendang.getPicpath();
                String path = request.getContextPath();
                String basePath = DbConfig.IP + path
                        + "/Temp/ArcticleList/";
                String serviceUrl = basePath + fileName;
                String urlpath ;
                if (operatingSystem.equals("Windows")){
                     urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\ArcticleList\\";
                }else {
                     urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/ArcticleList/";
                }

                serviceFilePath = urlpath + fileName;// 服务器文件
                FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
                FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
                // 如果目录中不存在文件，下载雷达文件到temp目录
                File serviceFile = new File(serviceFilePath);// 服务器文件
                if (!serviceFile.exists()) {// 把文件上传到服务器
                    Map<String, Object> queryMap = new HashMap<String, Object>();
                    queryMap.put("id", wendang.getId());
                    queryMap.put("table_name", "addwendang");
                    queryMap.put("collectionName", "image_file");
                    queryMap.put("advCode", DbConfig.advCode);
                    byte[] data = ms.selectData(queryMap);
                    if (data == null) {
                        serviceFilePath = "";
                    } else {
                        FileUtil.bytesToFile(data, serviceFilePath);
                    }
                }
                if (!serviceFilePath.equals("")) {
                    serviceFilePath = serviceUrl;
                }

                String imagepath = serviceFilePath;
                //添加图片
                wendang.setPicpath(imagepath);
            }
        } catch (Exception e) {
            return new ResultObj("查询失败", e.getMessage(), true);
        }
        return new ResultObj("查询成功", agrisrvList, true);
    }

    /**
     * @Description: 增加点击量
     * @Author: sunshine
     * @Date: 2021/7/22 16:19
     **/
    @Override
    public Object SetZhengFaClick(Addwendang updateData, String id) {
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataByUpdate<String, Addwendang> dataByUpdate = new RequestDataByUpdate<String, Addwendang>();
        try {
            dataByUpdate.setData(updateData);
            dataByUpdate.setParam("id='" + id + "'");
            selectParam.put("method", "addwendang");
            selectParam.put("sqlType", "update");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(dataByUpdate));
            String message = pc.processRequest(selectParam);
            if ("-1".equals(message)) {
                return new ResultObj("更新失败", "", true);
            }
            return new ResultObj("更新成功", message, true);
        } catch (Exception e) {
            return new ResultObj("更新失败", e.getMessage(), true);
        }
    }

    /**
     * @Description: 绑定发育期信息
     * @Author: sunshine
     * @Date: 2021/7/22 17:43
     **/
    @Override
    public Object BindNongQi(String stationid, String stationname, String forecaststationid) {
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<township_forecasttemp> agrisrvList = new ArrayList<township_forecasttemp>();
        try {
            selectRequest.setColumns(new String[]{"datechar", "timechar", "ntimes"});
            selectRequest.setParam("stationid='" + forecaststationid + "'");
            selectRequest.setSort(new String[]{"datechar desc,timechar desc,ntimes asc"});
            selectRequest.setLimit(1);
            selectParam.put("method", "township_forecast");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            agrisrvList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<township_forecasttemp>>() {
            });
            String Text = stationname + "农事预报<br>";
            if (agrisrvList.size() > 0) {
                DateTime startDate = new DateTime(agrisrvList.get(0).getDatechar());
                if (agrisrvList.get(0).getTimechar() == "20") {
                    startDate.AddDays(1);//发育期预报时间后推一天
                }
                DateTime endDate = startDate.AddDays(4);
                String strWhere = "";//条件
                strWhere = "joinstation = '" + stationid + "'";//站点过滤
                strWhere += String.format(" and ((to_char(growdatestarttime, 'MM-DD') >='%s' and to_char(growdateendtime,'MM-DD')<='%s') " +
                                "or (to_char(growdatestarttime, 'MM-DD') >='%s' and to_char(growdateendtime,'MM-DD')<='%s'))",
                        startDate.toDateTimeString("MM-dd"),startDate.toDateTimeString("MM-dd"),endDate.toDateTimeString("MM-dd"), endDate.toDateTimeString("MM-dd"));//发育期时间过滤,获取在这四天时间内的所有有利、不利条件信息
                selectRequest = new RequestDataBySelect();
                selectRequest.setParam(strWhere + "and indexcondition='温度' and datasource='预报'");
                //有利条件视图结果
                selectParam = new HashMap<String, String>();
                selectParam.put("method", "cropgrow_goodcondition_view");
                selectParam.put("sqlType", "select");
                selectParam.put("advCode", DbConfig.advCode);
                selectParam.put("param", JsonUtil.object2Json(selectRequest));
                message = pc.processRequest(selectParam);
                List<cropgrow_goodcondition_view> goodCondList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<cropgrow_goodcondition_view>>() {
                });
                //不利条件结果
                selectRequest = new RequestDataBySelect();
                selectRequest.setParam(strWhere + "and climatecondition='温度' and datasource='预报'");
                selectParam = new HashMap<String, String>();
                selectParam.put("method", "cropgrow_badcondition_view");
                selectParam.put("sqlType", "select");
                selectParam.put("advCode", DbConfig.advCode);
                selectParam.put("param", JsonUtil.object2Json(selectRequest));
                message = pc.processRequest(selectParam);
                List<cropgrow_badcondition_view> badCondList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<cropgrow_badcondition_view>>() {
                });
                //获取未来4天预报
                selectRequest = new RequestDataBySelect();
                selectRequest.setParam(String.format("datechar='%tF %tT' and timechar='%s' and stationid='%s'", agrisrvList.get(0).getDatechar(),agrisrvList.get(0).getDatechar(), agrisrvList.get(0).getTimechar(), forecaststationid));
                selectRequest.setSort(new String[]{"ntimes asc"});
                selectRequest.setLimit(8);
                selectParam = new HashMap<String, String>();
                selectParam.put("method", "township_forecast");
                selectParam.put("sqlType", "select");
                selectParam.put("param", JsonUtil.object2Json(selectRequest));
                message = pc.processRequest(selectParam);
                List<township_forecasttemp> fcstList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<township_forecasttemp>>() {
                });
                for (int i = 0; i < 4; i++) {
                    String ntime = String.valueOf(24 * i);
                    String datetime = new DateTime(agrisrvList.get(0).getDatechar()).AddDays(i).toDateTimeString("yyyy-MM-dd");
//                  Text += datetime + "<br>";
                    //获取12小时和24小时预报
                    township_forecasttemp township12 = fcstList.get(i * 2);
                    township_forecasttemp township24 = fcstList.get(i * 2 + 1);
                    double maxTemp = township12.getMaxtemp() > township24.getMaxtemp() ? township12.getMaxtemp() : township24.getMaxtemp();//当前预报时间最高温度
                    double minTemp = township12.getMintemp() > township24.getMintemp() ? township24.getMintemp() : township12.getMintemp();//当前预报时间最低晕都
                    //遍历所有作物发育期的有利条件
                    List<CropGrowDateInfo> zwfyq = new ArrayList<CropGrowDateInfo>();  //发育期信息最终保存地方
                    for (cropgrow_goodcondition_view goodItem : goodCondList) {
                        //判断是否能够达到有利条件
                        double limitTemp = goodItem.getWeatherconditionvalue();
                        if (FitGoodCondition(maxTemp, minTemp, limitTemp, String.valueOf(goodItem.getContrasttype()))) {
                            CropGrowDateInfo model = new CropGrowDateInfo();
                            model.setCropname(goodItem.getCropname().trim());
                            model.setGrowdatename(goodItem.getGrowdatename().trim());
                            model.setGoogcondition("当前气象信息为" + goodItem.getGoogcondition());
                            model.setSzsyx("1.gif");
                            model.setFfcs("");
                            zwfyq.add(model);
                            Text += model.getCropname() + "处于" + model.getGrowdatename() + "<br>";
                            Text += model.getGoogcondition() + model.getFfcs() + "<br>";
                        }

                    }
                    ;
                    //遍历所有作物发育期的不利条件
                    for (cropgrow_badcondition_view badItem : badCondList) {
                        double limitTemp = badItem.getClimateconditionvalue();
                        if (FitBadCondition(maxTemp, minTemp, limitTemp, String.valueOf(badItem.getContrasttype()))) {
                            CropGrowDateInfo model = new CropGrowDateInfo();
                            model.setCropname(badItem.getCropname().trim());
                            model.setGrowdatename(badItem.getGrowdatename().trim());
                            model.setGoogcondition("当前气象信息为" + badItem.getBadconditions());
                            model.setSzsyx("3.gif");
                            model.setFfcs(",防范措施为" + badItem.getDefendmeasure());
                            zwfyq.add(model);
                            Text += model.getCropname() + "处于" + model.getGrowdatename() + "<br>";
                            Text += model.getGoogcondition() + model.getFfcs() + "<br>";
                        }
                    }
                    //一天完结
                    if (zwfyq.size() == 0) {
                        Text += "暂无预报信息 或 在该日期下并不存在生长发育期中的农作物！<br>";
                    }
                }
            }
            return new ResultObj("查询成功", Text, true);
        } catch (Exception e) {
            return new ResultObj("查询失败", e.getMessage(), true);
        }
    }

    @Override
    public List<soil_humidity> GetSoilHumidity(String startDate, String endDate, String stationId) {
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<soil_humidity> agrisrvList = new ArrayList<soil_humidity>();
        try {
            selectParam = new HashMap<String, String>();
            selectRequest = new RequestDataBySelect();
            selectRequest.setColumns(new String[]{"observetime", "level", "stationid", "relhumidity"});
            StringBuilder builder = new StringBuilder();
            builder.append("1=1");
            if (!StringUtil.IsNullOrEmpty(startDate) && !StringUtil.IsNullOrEmpty(endDate)) {
                builder.append(" and observetime >= '" + startDate + "' and observetime <= '" + endDate + "'");
            }
            if (!StringUtil.IsNullOrEmpty(stationId)) {
                builder.append(" and stationid = '" + stationId + "'");
            }
            builder.append(" and relhumidity<>-65535");
            selectRequest.setParam(builder.toString());
            selectRequest.setSort(new String[]{" observetime asc,level"});
            selectParam.put("method", "soil_humidity");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            agrisrvList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<soil_humidity>>() {
            });

        } catch (Exception e) {

        }
       return agrisrvList;
    }

    /**
     * @Description: 获取农气预报
     * @Author: sunshine
     * @Date: 2021/7/23 13:40
     **/
    @Override
    public Object GetArgiFast(String nstype, HttpServletRequest request) {
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<agri_product> agrisrvList = new ArrayList<agri_product>();
        List<ImgInfo> img1 = new ArrayList<>();
        try {
            selectRequest.setColumns(new String[]{"id", "forecasttime"});
            if (!StringUtil.IsNullOrEmpty(nstype)) {
                selectRequest.setParam("producttype = '农事预报' and position('" + nstype + "' in productname) > 0");
            }
            selectRequest.setSort(new String[]{"forecasttime desc"});
            selectRequest.setLimit(1);
            selectParam.put("method", "agri_product");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            agrisrvList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<agri_product>>() {
            });
            if (agrisrvList.size() != 0) {
                String servicePath = "";// 服务器文件
                String urlpath ;
                if (operatingSystem.equals("Windows")){
                   urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Agri\\";// 临时文件目录
                }else {
                    urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Agri/";// 临时文件目录
                }

                FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
                FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
                ImgInfo info = new ImgInfo();
                String fileName = new DateTime(agrisrvList.get(0).getForecasttime()).toDateTimeString("yyyyMMddHH") + nstype + ".jpg";// 文件名
                String jpgPath = urlpath + fileName;
                File jpgFile = new File(jpgPath);
                if (jpgFile.exists()) {
                    if (operatingSystem.equals("Windows")){
                        servicePath = "Temp\\Agri\\" + fileName;
                    }else {
                        servicePath = "Temp/Agri/" + fileName;
                    }

                } else {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("id", agrisrvList.get(0).getId()+"");
                    map.put("table_name", "agri_product");
                    map.put("collectionName", "image_file");
                    map.put("advCode", DbConfig.advCode);
                    byte[] data = ms.selectData(map);
                    if (data == null) {
                        info.setName("暂无图片");
                        info.setPath("");
                        img1.add(info);
                        return new ResultObj("查询成功", img1, true);
                    }
                    FileUtil.bytesToFile(data, jpgPath);
                }
                info.setName(fileName.replace(".jpg", ""));
                String path = request.getContextPath();
                info.setPath(DbConfig.IP + path + "/" + servicePath.replace("\\", "/"));
                img1.add(info);
            }
        } catch (Exception e) {
            return new ResultObj("查询失败", e.getMessage(), true);
        }
        return new ResultObj("查询成功", img1, true);
    }

    /**
     * @Description: 查询土壤湿度站点
     * @Author: sunshine
     * @Date: 2021/7/23 15:33
     **/
    @Override
    public Object GetSoilHumiditySta() {
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<township_station> listbresult = new ArrayList<>();
        try {
            //selectRequest.setParam("observetime>='" + DateTime.now().AddDays(-9).toDateString() + "'");
            selectRequest.setColumns(new String[]{"distinct stationid"});
            selectParam.put("method", "soil_humidity");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message1 = pc.processRequest(selectParam);
            List<soil_humidity> lista = JsonUtil.jsonStr2TypeReference(message1, new TypeReference<List<soil_humidity>>() {
            });
            // b表
            selectParam = new HashMap<String, String>();
            selectRequest = new RequestDataBySelect();
            selectRequest.setColumns(new String[]{"distinct stationid", "stationname"});
            selectRequest.setParam("city like '" + DbConfig.CITY + "%'");
            selectParam.put("method", "smallscale_station");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            message1 = pc.processRequest(selectParam);
            List<smallscale_station> listb = JsonUtil.jsonStr2TypeReference(message1, new TypeReference<List<smallscale_station>>() {
            });
            for (smallscale_station itemb : listb) {
                for (soil_humidity itema : lista) {
                    if (itemb.getStationid().trim().equals(itema.getStationid().trim())) {
                        township_station t = new township_station();
                        t.setStationid(itemb.getStationid());
                        t.setStationname(itemb.getStationname());
                        listbresult.add(t);
                    }
                }
            }
        } catch (Exception e) {
            return new ResultObj("查询失败", e.getMessage(), true);
        }
        return new ResultObj("查询成功", listbresult, true);
    }

    /**
     * @Description: 获取视频列表
     * @Author: sunshine
     * @Date: 2021/7/23 16:45
     **/
    @Override
    public Object GetVideoList(String id) {
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<Video> agrisrvList = new ArrayList<Video>();
        try {
            selectRequest.setColumns(new String[]{"id", "bigtype", "smalltype", "title", "publisher", "videoname", "videopath", "datamodifydate", "finalmodifydate", "owner"});
            selectRequest.setParam("owner = '" + DbConfig.CITY + "'");
            if (!StringUtil.IsNullOrEmpty(id))
                selectRequest.setParam(selectRequest.getParam() + " and id = '" + id + "'");
            selectRequest.setSort(new String[]{"id desc"});
            selectParam.put("method", "video");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message1 = pc.processRequest(selectParam);
            agrisrvList = JsonUtil.jsonStr2TypeReference(message1, new TypeReference<List<Video>>() {
            });
        } catch (Exception e) {
            return new ResultObj("查询失败", e.getMessage(), true);
        }
        return new ResultObj("查询成功", agrisrvList, true);
    }

    /**
     * @Description: 获取农业服务产品
     * @Author: sunshine
     * @Date: 2021/7/23 16:58
     **/
    @Override
    public Object GetAgriChanpin(String nqsrvTypes, HttpServletRequest request) {
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<agri_product> agrisrvList = new ArrayList<agri_product>();
        try {
            selectRequest.setColumns(new String[]{"productname", "producttype", "id"});
            if (!StringUtil.IsNullOrEmpty(nqsrvTypes))
                selectRequest.setParam("producttype in (" + nqsrvTypes + ")");
            selectRequest.setSort(new String[]{"maketime desc"});
            selectParam.put("method", "agri_product");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
             String message1 = pc.processRequest(selectParam);
            agrisrvList = JsonUtil.jsonStr2TypeReference(message1, new TypeReference<List<agri_product>>() {
            });

            if (agrisrvList.size() != 0) {
                for (agri_product agri : agrisrvList) {
                    String servicePath = "";// 服务器文件

                    String urlpath ;
                    if (operatingSystem.equals("Windows")){
                         urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\AgriChanpin\\";// 临时文件目录
                    }else {
                         urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/AgriChanpin/";// 临时文件目录
                    }

                    FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
                    FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
                    String fileName = agri.getProductname();// 文件名
                    String[] split = fileName.split("[.]");
                    String fName = split[0] + "." + "pdf";
                    String jpgPath = urlpath + fName;
                    File jpgFile = new File(jpgPath);
                    if (jpgFile.exists()) {
                        if (operatingSystem.equals("Windows")){
                            servicePath = "Temp\\AgriChanpin\\" + fName;
                        }else {
                            servicePath = "Temp/AgriChanpin/" + fName;
                        }

                        String path = request.getContextPath();
                        agri.setProductpath(DbConfig.IP + path + "/" + servicePath.replace("\\", "/"));
                    } else {
                        Map<String, Object> map = new HashMap<String, Object>();
                         map.put("id", agri.getId()+"");
                        map.put("table_name", "agri_product");
                        map.put("collectionName", "pdf_file");
                        map.put("advCode", DbConfig.advCode);
                        byte[] data = ms.selectData(map);
                        if (data == null) {
                            agri.setProductpath("");
                        } else {
                            FileUtil.bytesToFile(data, jpgPath);
                            String path = request.getContextPath();
                            agri.setProductpath(DbConfig.IP + path + "/" + servicePath.replace("\\", "/"));
                        }
                    }
                }
            }
        } catch (Exception e) {
            return new ResultObj("查询失败", e.getMessage(), true);
        }
        return new ResultObj("查询成功", agrisrvList, true);
    }

    /**
     * @Description: 常规气象服务
     * @Author: sunshine
     * @Date: 2021/7/23 17:14
     **/
    @Override
    public Object GetAgriChanggui(String nqsrvTypes, HttpServletRequest request) {
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<summary_product> agrisrvList = new ArrayList<summary_product>();
        try {
            selectRequest.setColumns(new String[]{"productname", "producttype2", "id", "producttype"});
            if (!StringUtil.IsNullOrEmpty(nqsrvTypes))
                selectRequest.setParam("producttype in (" + nqsrvTypes + ")");
            selectRequest.setSort(new String[]{"maketime desc"});
            selectParam.put("method", "summary_product");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message1 = pc.processRequest(selectParam);
            agrisrvList = JsonUtil.jsonStr2TypeReference(message1, new TypeReference<List<summary_product>>() {
            });

            if (agrisrvList.size() != 0) {
                for (summary_product agri : agrisrvList) {
                    String servicePath = "";// 服务器文件
                    String urlpath ;
                    if (operatingSystem.equals("Windows")){
                         urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\AgriChanpin\\";// 临时文件目录
                    }else {
                         urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/AgriChanpin/";// 临时文件目录
                    }

                    FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
                    FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
                    String fileName = agri.getProductname();// 文件名
                    String[] split = fileName.split("[.]");
                    String fName = split[0] + "." + "pdf";
                    String jpgPath = urlpath + fName;
                    File jpgFile = new File(jpgPath);
                    if (jpgFile.exists()) {
                        if (operatingSystem.equals("Windows")){
                            servicePath = "Temp\\AgriChanpin\\" + fName;
                        }else {
                            servicePath = "Temp/AgriChanpin/" + fName;
                        }

                        String path = request.getContextPath();
                        agri.setProducttype2(DbConfig.IP + path + "/" + servicePath.replace("\\", "/"));
                    } else {
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("id", agri.getId()+"");
                        map.put("table_name", "summary_product");
                        map.put("collectionName", "pdf_file");
                        map.put("advCode", DbConfig.advCode);
                        byte[] data = ms.selectData(map);
                        if (data == null) {
                            agri.setProducttype2("");
                        } else {
                            FileUtil.bytesToFile(data, jpgPath);
                            String path = request.getContextPath();
                            agri.setProducttype2(DbConfig.IP + path + "/" + servicePath.replace("\\", "/"));
                        }
                    }
                }
            }
        } catch (Exception e) {
            return new ResultObj("查询失败", e.getMessage(), true);
        }
        return new ResultObj("查询成功", agrisrvList, true);
    }

    @Override
    public Object getQuHuaTu(String typeName, HttpServletRequest request) {
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();

        try {
            // 根据操作系统来设置文件路径
            String servicePath = ""; // 服务器文件路径
            String urlpath;
            if (operatingSystem.equals("Windows")) {
                urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Quhuatu\\"; // 临时文件目录
            } else {
                urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Quhuatu/"; // 临时文件目录
            }

            // 创建文件夹，生成多级目录
            FileUtil.mkDirs(urlpath);
            // 清除缓存
            FileUtil.ClearTempFiles(urlpath, 1000);

            // 根据 typeName 生成文件名
            String fileName = typeName + ".jpg"; // 假设图片格式为 .jpg
            String jpgPath = urlpath + fileName;
            File jpgFile = new File(jpgPath);

            // 如果图片已存在，直接返回路径
            if (jpgFile.exists()) {
                if (operatingSystem.equals("Windows")) {
                    servicePath = "Temp\\Quhuatu\\" + fileName;
                } else {
                    servicePath = "Temp/Quhuatu/" + fileName;
                }

                String path = request.getContextPath();
                return new ResultObj("查询成功", DbConfig.IP + path + "/" + servicePath.replace("\\", "/"), true);

            } else {
                // 图片不存在，从 MongoDB 获取
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("qh_type", typeName); // 使用 typeName 进行查询
                map.put("collectionName", "quhuatu_image_file"); // 假设你存储图片的集合为 "image_file"
                map.put("advCode", DbConfig.advCode);

                // 从 MongoDB 获取图片字节数据
                byte[] data = ms.selectData(map);
                if (data == null) {
                    return new ResultObj("查询失败", "图片未找到", false);
                } else {
                    // 保存图片到本地文件系统
                    FileUtil.bytesToFile(data, jpgPath);

                    // 生成返回的文件路径
                    if (operatingSystem.equals("Windows")) {
                        servicePath = "Temp\\Quhuatu\\" + fileName;
                    } else {
                        servicePath = "Temp/Quhuatu/" + fileName;
                    }

                    String path = request.getContextPath();
                    return new ResultObj("查询成功", DbConfig.IP + path + "/" + servicePath.replace("\\", "/"), true);
                }
            }
        } catch (Exception e) {
            return new ResultObj("查询失败", e.getMessage(), true);
        }
    }


    /**
     * @Description: 获取各种类型得区划图
     * @Author: sunshine
     * @Date: 2021/7/23 17:20
     **/
    @Override
    public Object getQhzhTable(String typeName, HttpServletRequest request) {
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<agri_product> agrisrvList = new ArrayList<agri_product>();
        try {
            selectRequest.setColumns(new String[]{"id", "productname"});
            if (!StringUtil.IsNullOrEmpty(typeName))
                selectRequest.setParam("producttype='" + typeName + "'");
            selectParam.put("method", "agri_product");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message1 = pc.processRequest(selectParam);
            agrisrvList = JsonUtil.jsonStr2TypeReference(message1, new TypeReference<List<agri_product>>() {
            });

            if (agrisrvList.size() != 0) {
                for (agri_product agri : agrisrvList) {
                    String servicePath = "";// 服务器文件
                    String urlpath ;
                    if (operatingSystem.equals("Windows")){
                         urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Quhuatu\\";// 临时文件目录
                    }else {
                         urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Quhuatu/";// 临时文件目录
                    }

                    FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
                    FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
                    String fileName = agri.getId() + "_" + agri.getProductname();// 文件名
                    String jpgPath = urlpath + fileName;
                    File jpgFile = new File(jpgPath);
                    if (jpgFile.exists()) {
                        if (operatingSystem.equals("Windows")){
                            servicePath = "Temp\\Quhuatu\\" + fileName;
                        }else {
                            servicePath = "Temp/Quhuatu/" + fileName;
                        }

                        String path = request.getContextPath();
                        agri.setProductpath(DbConfig.IP + path + "/" + servicePath.replace("\\", "/"));
                    } else {
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("id", agri.getId()+"");
                        map.put("collectionName", "image_file");
                        map.put("advCode", DbConfig.advCode);
                        byte[] data = ms.selectData(map);
                        if (data == null) {
                            agri.setProductpath("");
                        } else {
                            FileUtil.bytesToFile(data, jpgPath);
                            String path = request.getContextPath();
                            agri.setProductpath(DbConfig.IP + path + "/" + servicePath.replace("\\", "/"));
                        }
                    }
                }
            }
        } catch (Exception e) {
            return new ResultObj("查询失败", e.getMessage(), true);
        }
        return new ResultObj("查询成功", agrisrvList, true);
    }

    /**
     * @Description: 得到预警信息
     * @Author: sunshine
     * @Date: 2021/7/23 17:30
     **/
    @Override
    public Object getJCWarning(String id, String start, String end) {
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<warn_signal_info> warnMessageList = new ArrayList<warn_signal_info>();
        try {
            DateTime warnTime = DateTime.now().AddDays(-1);
            selectRequest = new RequestDataBySelect();
            StringBuilder builder = new StringBuilder();
            builder.append("bfree= 0 and (city like '" + DbConfig.CITY + "%')");
            if (!StringUtil.IsNullOrEmpty(id))
                builder.append(" and id = '" + id + "'");
            if (!StringUtil.IsNullOrEmpty(start))
                builder.append(" and announcedtime >= '" + start + "'");
            if (!StringUtil.IsNullOrEmpty(end))
                builder.append(" and announcedtime <= '" + end + "'");
            selectRequest.setParam(builder.toString());
            selectRequest.setLimit(1);
            selectRequest.setSort(new String[]{"announcedtime desc"});
            selectParam.put("method", "warn_signal_info");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            warnMessageList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<warn_signal_info>>() {
            });
        } catch (Exception e) {
            return new ResultObj("查询失败", e.getMessage(), true);
        }
        return new ResultObj("查询成功", warnMessageList, true);
    }

    /**
     * @Description: 获取监测评估产品图DataTable
     * @Author: sunshine
     * @Date: 2021/7/26 10:14
     **/
    @Override
    public Object getJcjgList(String typeName, HttpServletRequest request) {
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<agri_product> agrisrvList = new ArrayList<agri_product>();
        try {
            int limit = 3;//3天
            if (typeName.contains("湿度")) limit = 6;
            selectRequest.setColumns(new String[]{"id", "productname"});
            if (!StringUtil.IsNullOrEmpty(typeName))
                selectRequest.setParam("producttype='" + typeName + "'");
            selectRequest.setSort(new String[]{"maketime desc"});
            selectRequest.setLimit(limit);
            selectParam.put("method", "agri_product");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message1 = pc.processRequest(selectParam);
            agrisrvList = JsonUtil.jsonStr2TypeReference(message1, new TypeReference<List<agri_product>>() {
            });

            if (agrisrvList.size() != 0) {
                for (agri_product agri : agrisrvList) {
                    String servicePath = "";// 服务器文件
                    String urlpath ;
                    if (operatingSystem.equals("Windows")){
                         urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Turang\\";// 临时文件目录
                    }else {
                         urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Turang/";// 临时文件目录
                    }

                    FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
                    FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
                    String fileName = agri.getId() + "_" + agri.getProductname();// 文件名
                    if (fileName.contains(".doc")) {
                        fileName = fileName.replace(".doc", ".jpg");//doc得图片产品
                    } else if (!fileName.contains(".")) {
                        fileName = fileName + ".jpg";//默认图片
                    }
                    String jpgPath = urlpath + fileName;
                    File jpgFile = new File(jpgPath);
                    if (jpgFile.exists()) {
                        if (operatingSystem.equals("Windows")){
                            servicePath = "Temp\\Turang\\" + fileName;
                        }else {
                            servicePath = "Temp/Turang/" + fileName;
                        }

                        String path = request.getContextPath();
                        agri.setProductpath(DbConfig.IP + path + "/" + servicePath.replace("\\", "/"));
                    } else {
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("id", agri.getId()+"");
                        map.put("collectionName", "image_file");
                        map.put("advCode", DbConfig.advCode);
                        byte[] data = ms.selectData(map);
                        if (data == null) {
                            agri.setProductpath("");
                        } else {
                            FileUtil.bytesToFile(data, jpgPath);
                            String path = request.getContextPath();
                            agri.setProductpath(DbConfig.IP + path + "/" + servicePath.replace("\\", "/"));
                        }
                    }
                    agri.setProductname(fileName.replace(".jpg", ""));
                }
            }
        } catch (Exception e) {
            return new ResultObj("查询失败", e.getMessage(), true);
        }
        return new ResultObj("查询成功", agrisrvList, true);
    }

    /**
    * @Description: 得到指标库
    * @Author: sunshine
    * @Date: 2021/7/26 10:51
    **/
    @Override
    public Object getCropIndexlibList(String zhinames, int parseInt) {
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        int len = 15 * (parseInt);
        try {
            if(zhinames.equals("1")){
                List<CropGrowdateIndexlib> warnMessageList = new ArrayList<CropGrowdateIndexlib>();
                List<CropGrowdateIndexlib> resultList = new ArrayList<CropGrowdateIndexlib>();
                selectRequest.setColumns(new String[]{"indexid", "cropname", "type", "growdatename", "growdatestarttime", "growdateendtime"});
                selectRequest.setSort(new String[]{"growdatestarttime desc"});
                selectParam.put("method", "crop_growdate_indexlib");
                selectParam.put("sqlType", "select");
                selectParam.put("advCode", DbConfig.advCode);
                selectParam.put("param", JsonUtil.object2Json(selectRequest));
                String message = pc.processRequest(selectParam);
                warnMessageList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<CropGrowdateIndexlib>>() {
                });
                int rowCount = warnMessageList.size();
                int lent = 0;
                if ((len + 15) > rowCount)
                {
                    lent = rowCount;
                }
                else
                {
                    lent = len + 15;
                }
                if (len <= lent) {
                    for (int i = len; i < lent; i++)
                    {
                        resultList.add(warnMessageList.get(i));
                    }
                }else{
                    for (int i = 0; i < lent; i++)
                    {
                        resultList.add(warnMessageList.get(i));
                    }
                }
                return new ResultObj("查询成功", resultList, true);
            }else if(zhinames.equals("2")){
                selectParam = new HashMap<String, String>();
                selectRequest = new RequestDataBySelect();
                List<CropDistIndex> warnMessageList = new ArrayList<CropDistIndex>();
                List<CropDistIndex> resultList = new ArrayList<CropDistIndex>();
                selectRequest.setColumns(new String[]{"cropname", "diseasesname", "starttime","endtime"});
                selectRequest.setSort(new String[]{"starttime desc"});
                selectParam.put("method", "crop_dist_index");
                selectParam.put("sqlType", "select");
                selectParam.put("advCode", DbConfig.advCode);
                selectParam.put("param", JsonUtil.object2Json(selectRequest));
                String message = pc.processRequest(selectParam);
                warnMessageList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<CropDistIndex>>() {
                });
                int rowCount = warnMessageList.size();
                int lent = 0;
                if ((len + 15) > rowCount)
                {
                    lent = rowCount;
                }
                else
                {
                    lent = len + 15;
                }
                if (len <= lent) {
                    for (int i = len; i < lent; i++)
                    {
                        resultList.add(warnMessageList.get(i));
                    }
                }else{
                    for (int i = 0; i < lent; i++)
                    {
                        resultList.add(warnMessageList.get(i));
                    }
                }

                return new ResultObj("查询成功", resultList, true);
            }else if(zhinames.equals("3")){
                selectParam = new HashMap<String, String>();
                selectRequest = new RequestDataBySelect();
                List<CropWeatherDistIndexlib> warnMessageList = new ArrayList<CropWeatherDistIndexlib>();
                List<CropWeatherDistIndexlib> resultList = new ArrayList<CropWeatherDistIndexlib>();
                selectRequest.setColumns(new String[]{"id", "cropname", "growthdate", "easyhappentype", "disaeasyhappencondition", "disastarttime", "disaendtime"});
                selectParam.put("method", "crop_weather_dist_indexlib");
                selectParam.put("sqlType", "select");
                selectParam.put("advCode", DbConfig.advCode);
                selectParam.put("param", JsonUtil.object2Json(selectRequest));
                String message = pc.processRequest(selectParam);
                warnMessageList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<CropWeatherDistIndexlib>>() {
                });
                for (CropWeatherDistIndexlib indexlib : warnMessageList) {
                    indexlib.setGrowthdate(indexlib.getGrowthdate());
                }
                int rowCount = warnMessageList.size();
                int lent = 0;
                if ((len + 15) > rowCount)
                {
                    lent = rowCount;
                }
                else
                {
                    lent = len + 15;
                }
                if (len <= lent) {
                    for (int i = len; i < lent; i++)
                    {
                        resultList.add(warnMessageList.get(i));
                    }
                }else{
                    for (int i = 0; i < lent; i++)
                    {
                        resultList.add(warnMessageList.get(i));
                    }
                }
                return new ResultObj("查询成功", resultList, true);
            }
        } catch (Exception e) {
            return new ResultObj("查询失败", e.getMessage(), true);
        }
        return  new ResultObj("查询失败", "未传递zhinames", true);
    }

    /**
    * @Description: 根据大类别获取小类别
    * @Author: sunshine
    * @Date: 2021/7/26 11:19
    **/
    @Override
    public Object getSmallType(String parentId,String smallId,HttpServletRequest request) {
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<Addwendang> warnMessageList = new ArrayList<Addwendang>();
        try {
            if (!StringUtil.IsNullOrEmpty(parentId))
                selectRequest.setParam(" bigtype = '" + parentId + "' and smalltype = '" + smallId + "'");
            selectRequest.setSort(new String[]{"sort desc"});
            selectParam.put("method", "addwendang");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            warnMessageList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<Addwendang>>() {
            });
            for (Addwendang wendang : warnMessageList) {
                String serviceFilePath = "";
                // 下载
                String fileName = wendang.getPicpath();
                String path = request.getContextPath();
                String basePath = DbConfig.IP + path
                        + "/Temp/ArcticleList/";
                String serviceUrl = basePath + fileName;
                String urlpath ;
                if (operatingSystem.equals("Windows")){
                     urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\ArcticleList\\";
                }else {
                     urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/ArcticleList/";
                }

                serviceFilePath = urlpath + fileName;// 服务器文件
                FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
                FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
                // 如果目录中不存在文件，下载雷达文件到temp目录
                File serviceFile = new File(serviceFilePath);// 服务器文件
                if (!serviceFile.exists()) {// 把文件上传到服务器
                    Map<String, Object> queryMap = new HashMap<String, Object>();
                    queryMap.put("id", wendang.getId());
                    queryMap.put("table_name", "addwendang");
                    queryMap.put("collectionName", "image_file");
                    queryMap.put("advCode", DbConfig.advCode);
                    byte[] data = ms.selectData(queryMap);
                    if (data == null) {
                        serviceFilePath = "";
                    } else {
                        FileUtil.bytesToFile(data, serviceFilePath);
                    }
                }
                if (!serviceFilePath.equals("")) {
                    serviceFilePath = serviceUrl;
                }

                String imagepath = serviceFilePath;
                //添加视频路径
                wendang.setPicpath(imagepath);
            }
        } catch (Exception e) {
            return new ResultObj("查询失败", e.getMessage(), true);
        }
        return new ResultObj("查询成功", warnMessageList, true);
    }

    @Override
    public Object getWarningInfo() {
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<warinInfo> warnMessageList = new ArrayList<warinInfo>();
        try {
            selectRequest = new RequestDataBySelect();
            StringBuilder builder = new StringBuilder();
            selectRequest.setColumns(new String[]{"standard", "announcedtime", });
            builder.append("bfree= 0 and (city like '" + DbConfig.CITY + "%')");
            selectRequest.setParam(builder.toString());

            selectParam.put("method", "warn_signal_info");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = pc.processRequest(selectParam);
            warnMessageList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<warinInfo>>() {
            });
        } catch (Exception e) {
            return new ResultObj("查询失败", e.getMessage(), true);
        }
        return new ResultObj("查询成功", warnMessageList, true);
    }

    /// <summary>
    /// 获取不利条件（温度要素）比较结果
    /// 区极值
    /// </summary>
    /// <param name="maxTemp">预报最高温度</param>
    /// <param name="minTemp">预报最低问题</param>
    /// <param name="limitValue">阈值</param>
    /// <param name="compareType">比较类型</param>
    /// <returns></returns>
    public boolean FitBadCondition(double maxTemp, double minTemp, double limitValue, String compareType) {
        switch (Integer.parseInt(compareType)) {
            case 0://大于
                return limitValue > maxTemp;
            case 1://小于
                return limitValue < minTemp;
            case 2://等于
                return limitValue == maxTemp || limitValue == minTemp;
            case 3://大于等于
                return limitValue >= maxTemp;
            case 4://小于等于
                return limitValue <= minTemp;
            default:
                return false;
        }
    }

    /// <summary>
    /// 获取有利条件（温度要素）比较结果
    /// 取中间值
    /// </summary>
    /// <param name="maxTemp">预报最高温度</param>
    /// <param name="minTemp">预报最低问题</param>
    /// <param name="limitValue">阈值</param>
    /// <param name="compareType">比较类型</param>
    /// <returns></returns>
    public Boolean FitGoodCondition(double maxTemp, double minTemp, double limitValue, String compareType) {
        switch (Integer.parseInt(compareType)) {
            case 0://大于
                return limitValue > minTemp;
            case 1://小于
                return limitValue < maxTemp;
            case 2://等于
                return limitValue == maxTemp || limitValue == minTemp;
            case 3://大于等于
                return limitValue >= minTemp;
            case 4://小于等于
                return limitValue <= maxTemp;
            default:
                return false;
        }
    }

}
